<?php
declare (strict_types = 1);

namespace app\common\command;

use app\common\model\pachong\PachongProxyIp;
use app\common\model\pachong\tianqiyubao\PachongTianqiyubaoArea;
use app\common\model\pachong\tianqiyubao\PachongTianqiyubaoInfo;
use app\common\model\RedisService;
use app\common\model\Tool;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class CommandTianqiyubao3 extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('hello')
            ->setDescription('the hello command');
    }

    protected function execute(Input $input, Output $output)
    {
        $eday = date("Y-m-d", time());

        // 获取所有的地区
        $areaObjs = PachongTianqiyubaoArea::instance()->where([['id', 'between', [3000, 9000]]])->select()->toArray();
        foreach ($areaObjs as $areaObj){
            // 获取这个地区已经刷新时间的最大天数
            $PachongTianqiyubaoInfoObj = PachongTianqiyubaoInfo::instance()->where(['area_id'=>$areaObj['id']])->order('day desc')->findOrEmpty()->toArray();
            // 判断一下需要循环多少天,默认从2018.1.1开始获取数据
            $sday = $PachongTianqiyubaoInfoObj['day'] ?? "2018-01-01";

            if($eday != $sday){
                $dayArr = Tool::getDayRangeArr($sday,$eday);
                foreach ($dayArr as $day){
                    if($day == $sday){
                        continue;
                    }
                    $result = $this->getContent($areaObj,$day);
                    if(!empty($result)){
                        $result['area_id'] = $areaObj['id'];
                        $result['area_name'] = $areaObj['name'];
                        $result['day'] = $day;
                    }
                    PachongTianqiyubaoInfo::instance()->insert($result);
                }
            }
        }

        // 指令输出
        $output->writeln('hello');
    }


    public function getContent($areaObj,$day)
    {
        $ProxyIp = PachongProxyIp::instance()->getProxyIp();
        $areaObj['url'] = str_replace(".html","",$areaObj['url']);
        $areaObj['url'] = str_replace("lishi/","",$areaObj['url']);
        $url = "127.0.0.1:8000" . PachongTianqiyubaoInfo::$pythonUrl . "?proxy_ip=".$ProxyIp."&url=" . $areaObj['web_url'].$areaObj['url'] . "/" . date("Ymd",strtotime($day)) . ".html";

        $time = date("Y-m-d H:i:s", time());
        echo "【{$time}】执行python请求地址:".$url.PHP_EOL;
        $result = Tool::getCurl($url);
        $time = date("Y-m-d H:i:s", time());
        echo "【{$time}】执行python返回值:".json_encode($result,JSON_UNESCAPED_UNICODE).PHP_EOL;
        if($result == null){
            sleep(10);
            return $this->getContent($areaObj,$day);
        }
        if($result['code'] == 200){
            return $result['data'];
        }elseif ($result['code'] == 500){
            sleep(10);
            return $this->getContent($areaObj,$day);
        }else{
            return array();
        }
    }

}
